package com.fordmotor.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.fordmotor.config.BaseConfig;
import com.fordmotor.constant.WechatEnum;
import com.fordmotor.pojo.AccessTokenVO;
import com.fordmotor.pojo.WxchatUser;
import com.fordmotor.service.WechatService;
import com.fordmotor.util.HttpPostUtil;
import com.github.kevinsawicki.http.HttpRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Service;

import java.util.Map;
@Slf4j
@Primary
@Service
public class WechatServiceImpl implements WechatService {
    /**
     * 通过token获取用户信息
     * @param token
     * @return
     */
    @Override
    public WxchatUser getUserInfo(Map token){
        StringBuffer urlUser =  new StringBuffer("https://api.weixin.qq.com/sns/userinfo");
        //构建请求数据
        urlUser.append("access_token="+token.get("access_token"));
        urlUser.append("openid="+token.get("openid"));
        urlUser.append("lang="+"zh_CN");
        //调用httpclient处理请求得到用户信息json数据
        String user = HttpPostUtil.sendGet(urlUser.toString());
        //转换成用户对象
        WxchatUser wxchatUser = JSONObject.parseObject(user, WxchatUser.class);
        return wxchatUser;
    }
    /**
     * 刷新token处理
     * @return
     */
    @Override
    public Map refrehToken(String appid, String refresh_token){
        StringBuffer urlRefresh = new StringBuffer("https://api.weixin.qq.com/sns/oauth2/refresh_token?");
        //构建请求参数
        urlRefresh.append("appid="+appid);
        urlRefresh.append("&grant_type=refresh_token");
        urlRefresh.append("&refresh_token="+refresh_token);
        //调用httpclient发出请求
        Map refreshToken = (Map)JSONObject.parse(HttpPostUtil.sendGet(urlRefresh.toString()));
        return refreshToken;
    }
    @Override
    public AccessTokenVO getAccessToken(String code) {
        if (code == null) {
            return null;
        }
        String url = String.format(BaseConfig.getAccessTokenUrl(code), BaseConfig.getAppId(), BaseConfig.getSecret(), code);
        try {
            String result = HttpRequest.get(url).body();
            log.info("getWechatAccessToken result:{}", result);
            AccessTokenVO token = JSON.parseObject(result, AccessTokenVO.class);
            if (token.getErrCode() == null || WechatEnum.SUCCESS.equals(token.getErrCode())) {
                token.setOpenId(BaseConfig.getOpenId());
                log.info("get wechat access token:{}", token);
                return token;
            } else {
                log.warn("code {} request wechat api get access token error:{}", code, token);
            }
        } catch (Exception ex) {
            log.error("getWechatAccessToken error", ex);
        }
        return null;
    }

}
